package com.test;

import cn.hutool.core.util.StrUtil;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.util.Arrays;
import java.util.List;

public class ListMetrics {
    public static void main(String[] args) throws Exception {
        String host = "localhost";
        int port = 9001;

        // 构造JMXServiceURL
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi");

        // 连接到JMX代理
        JMXConnector connector = JMXConnectorFactory.connect(url);
        MBeanServerConnection connection = connector.getMBeanServerConnection();

        // 构造ObjectName，指定要查询的MBean
        ObjectName objectName = new ObjectName("org.springframework.boot:type=Endpoint,name=Metrics");

        // 调用listNames()方法

        Object listNames = connection.invoke(objectName, "listNames", new Object[]{}, new String[]{});


        // 输出结果
        String listName = listNames.toString();
        List<String> split = StrUtil.split(StrUtil.removeAll(StrUtil.removeAll(listName, "{names=["), "]}"), ", ");

        for (String metric : split) {

            ObjectName objectName1 = new ObjectName("org.springframework.boot:type=Endpoint,name=Metrics");
            Object value = connection.invoke(objectName1, "metric", new Object[]{metric}, new String[]{String.class.getName()});

            System.out.println(value);
        }

        // 关闭连接
        connector.close();
    }
}